#include "stm32f10x.h"                  // Device header
#include "Key.h"

uint16_t Time_10ms = 0;

void Timer_Init(void)
{
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);

    TIM_InternalClockConfig(TIM2);

    // 1ms Timer
    TIM_TimeBaseInitTypeDef TIM_TimeBaseInitstructure;
    TIM_TimeBaseInitstructure.TIM_ClockDivision = TIM_CKD_DIV1;
    TIM_TimeBaseInitstructure.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseInitstructure.TIM_Period = 100 - 1;                // maximum
    TIM_TimeBaseInitstructure.TIM_Prescaler = 720 - 1;              // pre division
    TIM_TimeBaseInitstructure.TIM_RepetitionCounter = 0;             // only applays to NB Timer(Tim1 and Tim8 in APB2)
    TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitstructure);              /*已初始化就进入中断原因 Generate an update event to reload the Prescaler and the Repetition counter values immediately */
    TIM_ClearFlag(TIM2, TIM_FLAG_Update);                            // clear 更新flag to 避免马上进入更新中断

    TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);

    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);

    NVIC_InitTypeDef NVIC_InitStructure;
    NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2;
    NVIC_Init(&NVIC_InitStructure);

    TIM_Cmd(TIM2, ENABLE);

}

/* IT templete
void TIM2_IRQHandler(void)
{
    if (TIM_GetFlagStatus(TIM2, TIM_FLAG_Update) == SET)
    {

        TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
    }
}
*/

// 用于减速
void TIM2_IRQHandler(void)
{
    if (TIM_GetFlagStatus(TIM2, TIM_FLAG_Update) == SET)
    {
        if (++Time_10ms == 10)
        {
            Time_10ms = 0;
            Key1_Val = GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_11);  
            Key1_Dowm = ~Key1_Val & (Key1_Val ^ Key1_OldVal);
            Key1_Up = Key1_Val & (Key1_Val ^ Key1_OldVal);
            Key1_OldVal = Key1_Val;

            Key2_Val = GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_0);  
            Key2_Dowm = ~Key2_Val & (Key2_Val ^ Key2_OldVal);
            Key2_Up = Key2_Val & (Key2_Val ^ Key2_OldVal);
            Key2_OldVal = Key2_Val;
        }

        TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
    }
}
